#!/usr/bin/env node
// @ts-check
const path = require('path');
const cp = require('child_process');
const fs = require('fs');

const extScriptsPck = require(path.resolve(__dirname, 'package.json'));

function getExtScript() {
    const commandIndex = process.argv.findIndex(arg => arg.endsWith('cell-component')) + 1;
    const args = process.argv.slice(commandIndex);

    if (!args[0]) {
        throw new Error('Please specify the script that runs with cell-component command.');
    }
    const script = 'ext:' + args[0];
    if (!(script in extScriptsPck.scripts)) {
        throw new Error('The ext script does not exist: ' + script);
    }
    return [extScriptsPck.scripts[script], ...args.slice(1, args.length)].join(' ');
}

function run(script) {
    return new Promise((resolve, reject) => {
        const env = Object.assign({}, process.env);
        const scriptProcess = cp.exec(script, {
            env,
            cwd: process.cwd()
        });
        // @ts-ignore
        scriptProcess.stdout?.pipe(process.stdout);
        // @ts-ignore
        scriptProcess.stderr?.pipe(process.stderr);
        scriptProcess.on('error', reject);
        scriptProcess.on('close', resolve);
    });
}

(async () => {
    let exitCode = 0;
    let extScript = undefined;
    try {
        extScript = getExtScript()
            .replace(/{{ROOT}}/g, __dirname)
            .replace(/{{TSCONFIGFILE}}/g, fs.existsSync('compile.tsconfig.json') ? 'compile.tsconfig.json' : 'tsconfig.json')
        exitCode = await run(extScript);
    } catch (err) {
        if (extScript) {
            console.error(`Error occurred in cell-component when executing: '${extScript}'`, err);
        } else {
            console.error('Error occurred in cell-component', err);
        }
        console.log(`${err.name}: ${err.message}`);
        exitCode = 1;
    }
    process.exit(exitCode);
})();